<template>
  <div class="browse-page">
    <!-- 页面标题 -->
    <div class="browse-header">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900">
              民法典浏览
            </h1>
            <p class="text-gray-600 mt-1">
              按编章结构浏览全部条文
            </p>
          </div>
          
          <!-- 编筛选器 -->
          <div class="hidden md:block">
            <select 
              v-model="browseStore.selectedPart" 
              class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-gray-50 text-gray-900"
              @change="handlePartChange"
            >
              <option value="">
                全部编
              </option>
              <option
                v-for="part in browseStore.partNames"
                :key="part"
                :value="part"
              >
                {{ part }}
              </option>
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="browse-content">
      <div class="container mx-auto px-4">
        <!-- 加载状态 -->
        <div
          v-if="browseStore.loading"
          class="flex justify-center py-8"
        >
          <LoadingSpinner />
        </div>

        <!-- 错误状态 -->
        <div
          v-else-if="browseStore.error"
          class="text-center py-8"
        >
          <div class="text-red-600 mb-4">
            {{ browseStore.error }}
          </div>
          <button 
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            @click="loadData"
          >
            重新加载
          </button>
        </div>

        <!-- 桌面端：双栏布局 -->
        <div
          v-else
          class="hidden lg:block"
        >
          <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
            <!-- 左侧：章节导航 -->
            <div class="lg:col-span-1">
              <div class="sticky top-4 bg-white border border-gray-200 rounded-lg p-4 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                  章节导航
                </h3>
                <div class="space-y-2 max-h-[70vh] overflow-y-auto chapter-scroll">
                  <template
                    v-for="(chapters, part) in browseStore.filteredChapters"
                    :key="part"
                  >
                    <div class="part-group">
                      <div class="part-title font-medium text-gray-900 py-2 border-b border-gray-100">
                        {{ part }}
                      </div>
                      <div class="chapters ml-2 mt-1 space-y-1">
                        <button
                          v-for="chapter in chapters"
                          :key="`${part}-${chapter.chapter_number}`"
                          :class="[
                            'w-full text-left px-3 py-2 rounded text-sm transition-colors chapter-btn',
                            isCurrentChapter(part, chapter.chapter_number)
                              ? 'bg-blue-100 text-blue-700'
                              : 'text-gray-600 hover:bg-gray-50'
                          ]"
                          @click="selectChapter(part, chapter.chapter_number)"
                        >
                          第{{ chapter.chapter_number }}章
                          <span class="text-xs text-gray-500 ml-1">
                            ({{ chapter.article_count }}条)
                          </span>
                        </button>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 右侧：条文列表 -->
            <div class="lg:col-span-3">
              <div
                v-if="!browseStore.currentPart"
                class="text-center py-12"
              >
                <BookOpenIcon class="mx-auto h-12 w-12 text-gray-400 mb-4" />
                <h3 class="text-lg font-medium text-gray-900 mb-2">
                  选择章节开始浏览
                </h3>
                <p class="text-gray-600">
                  从左侧导航中选择要浏览的章节
                </p>
              </div>

              <div v-else>
                <!-- 章节标题 -->
                <div class="flex items-center justify-between mb-6">
                  <div>
                    <h2 class="text-xl font-semibold text-gray-900">
                      {{ browseStore.currentPart }} 第{{ browseStore.currentChapter }}章
                    </h2>
                    <p class="text-gray-600 mt-1">
                      共 {{ browseStore.totalArticles }} 条
                    </p>
                  </div>
                </div>

                <!-- 条文列表 -->
                <div
                  v-if="browseStore.articlesLoading"
                  class="flex justify-center py-8"
                >
                  <LoadingSpinner />
                </div>

                <div
                  v-else-if="browseStore.currentChapterArticles.length === 0"
                  class="text-center py-8"
                >
                  <DocumentIcon class="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <p class="text-gray-600">
                    该章节暂无条文
                  </p>
                </div>

                <div
                  v-else
                  class="space-y-4"
                >
                  <ArticleCard
                    v-for="article in browseStore.currentChapterArticles"
                    :key="article._id"
                    :article="article"
                    @click="goToArticle(article)"
                  />

                  <!-- 分页 -->
                  <Pagination
                    v-if="browseStore.totalPages > 1"
                    :current-page="browseStore.currentPage"
                    :total-pages="browseStore.totalPages"
                    :total="browseStore.totalArticles"
                    @page-change="handlePageChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 移动端：手风琴布局 -->
        <div class="lg:hidden">
          <!-- 编筛选器（移动端） -->
          <div class="mb-4">
            <select 
              v-model="browseStore.selectedPart" 
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-gray-50 text-gray-900"
              @change="handlePartChange"
            >
              <option value="">
                全部编
              </option>
              <option
                v-for="part in browseStore.partNames"
                :key="part"
                :value="part"
              >
                {{ part }}
              </option>
            </select>
          </div>

          <!-- 手风琴式章节列表 -->
          <div class="space-y-4">
            <template
              v-for="(chapters, part) in browseStore.filteredChapters"
              :key="part"
            >
              <div class="border border-gray-200 rounded-lg overflow-hidden">
                <!-- 编标题 -->
                <button
                  class="w-full px-4 py-4 bg-gray-50 text-left font-medium text-gray-900 flex items-center justify-between"
                  @click="togglePart(part)"
                >
                  <span>{{ part }}</span>
                  <ChevronDownIcon 
                    :class="[
                      'h-5 w-5 transition-transform',
                      expandedParts.includes(part) ? 'rotate-180' : ''
                    ]"
                  />
                </button>

                <!-- 章节列表 -->
                <div
                  v-if="expandedParts.includes(part)"
                  class="p-4 border-t border-gray-200"
                >
                  <div class="grid grid-cols-2 gap-2">
                    <button
                      v-for="chapter in chapters"
                      :key="`${part}-${chapter.chapter_number}`"
                      :class="[
                        'px-3 py-2 text-sm rounded border transition-colors chapter-btn',
                        isCurrentChapter(part, chapter.chapter_number)
                          ? 'border-blue-500 bg-blue-50 text-blue-700'
                          : 'border-gray-200 text-gray-700 hover:bg-gray-50'
                      ]"
                      @click="selectChapter(part, chapter.chapter_number)"
                    >
                      第{{ chapter.chapter_number }}章
                      <div class="text-xs text-gray-500">
                        {{ chapter.article_count }}条
                      </div>
                    </button>
                  </div>
                </div>
              </div>
            </template>
          </div>

          <!-- 当前章节条文（移动端） -->
          <div
            v-if="browseStore.currentPart"
            class="mt-6"
          >
            <div class="bg-white border border-gray-200 rounded-lg p-4">
              <h3 class="font-semibold text-gray-900 mb-4">
                {{ browseStore.currentPart }} 第{{ browseStore.currentChapter }}章
              </h3>

              <div
                v-if="browseStore.articlesLoading"
                class="flex justify-center py-4"
              >
                <LoadingSpinner />
              </div>

              <div
                v-else-if="browseStore.currentChapterArticles.length === 0"
                class="text-center py-4"
              >
                <p class="text-gray-600">
                  该章节暂无条文
                </p>
              </div>

              <div
                v-else
                class="space-y-3"
              >
                <ArticleCard
                  v-for="article in browseStore.currentChapterArticles"
                  :key="article._id"
                  :article="article"
                  @click="goToArticle(article)"
                />

                <!-- 分页（移动端） -->
                <Pagination
                  v-if="browseStore.totalPages > 1"
                  :current-page="browseStore.currentPage"
                  :total-pages="browseStore.totalPages"
                  :total="browseStore.totalArticles"
                  @page-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBrowseStore } from '@/stores/browse'
import { BookOpenIcon, DocumentIcon, ChevronDownIcon } from '@heroicons/vue/24/outline'
import ArticleCard from '@/components/article/ArticleCard.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import Pagination from '@/components/common/Pagination.vue'

// 路由和store
const route = useRoute()
const router = useRouter()
const browseStore = useBrowseStore()

// 本地状态
const expandedParts = ref([])

// 方法
const loadData = async () => {
  await browseStore.loadChapters()
  
  // 如果路由中有章节参数，自动选择
  if (route.params.chapter) {
    const [part, chapterNumber] = route.params.chapter.split('-')
    if (part && chapterNumber) {
      await selectChapter(part, parseInt(chapterNumber))
    }
  }
}

const selectChapter = async (part, chapterNumber) => {
  await browseStore.loadChapterArticles(part, chapterNumber)
  
  // 更新路由（不触发页面重载）
  const chapterParam = `${part}-${chapterNumber}`
  if (route.params.chapter !== chapterParam) {
    router.replace({ name: 'BrowseChapter', params: { chapter: chapterParam } })
  }
  
  // 移动端：确保对应的编是展开的
  if (!expandedParts.value.includes(part)) {
    expandedParts.value.push(part)
  }
}

const isCurrentChapter = (part, chapterNumber) => {
  return browseStore.currentPart === part && browseStore.currentChapter === chapterNumber
}

const togglePart = (part) => {
  const index = expandedParts.value.indexOf(part)
  if (index > -1) {
    expandedParts.value.splice(index, 1)
  } else {
    expandedParts.value.push(part)
  }
}

const handlePartChange = () => {
  browseStore.clearCurrentChapter()
  // 清空路由参数
  if (route.params.chapter) {
    router.replace({ name: 'Browse' })
  }
}

const handlePageChange = (page) => {
  browseStore.goToPage(page)
}

const goToArticle = (article) => {
  router.push({ 
    name: 'Article', 
    params: { id: article.article_number } 
  })
}

// 监听路由变化
watch(() => route.params.chapter, async (newChapter, oldChapter) => {
  if (newChapter && newChapter !== oldChapter) {
    const [part, chapterNumber] = newChapter.split('-')
    if (part && chapterNumber) {
      await selectChapter(part, parseInt(chapterNumber))
    }
  } else if (!newChapter && oldChapter) {
    browseStore.clearCurrentChapter()
  }
})

// 生命周期
onMounted(async () => {
  await loadData()
})
</script>

<style scoped>
.browse-page {
  @apply min-h-screen bg-gray-50;
}

.browse-header {
  @apply bg-white border-b border-gray-200;
}

.browse-content {
  @apply py-6;
}

.part-group {
  @apply mb-4;
}

.part-title {
  @apply font-medium text-gray-900 py-2 border-b border-gray-100;
}

.chapters {
  @apply bg-white rounded-b-lg border-l border-r border-b border-gray-200;
}

/* 移动端手风琴样式 */
@media (max-width: 1023px) {
  .browse-content {
    @apply py-4;
  }
}

/* 章节按钮悬停效果 */
.chapter-btn {
  @apply transition-all duration-200 ease-in-out;
}

.chapter-btn:hover {
  @apply transform translate-y-[-1px] shadow-sm;
}

/* 分页组件样式调整 */
:deep(.pagination-container) {
  @apply flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mt-6 pt-4 border-t border-gray-200;
}

:deep(.pagination-info) {
  @apply text-sm text-gray-600;
}

:deep(.pagination-nav) {
  @apply flex items-center;
}

/* 粘性导航样式 */
.sticky {
  @apply top-4;
}

@media (min-width: 1024px) {
  .sticky {
    position: -webkit-sticky;
    position: sticky;
    top: 1rem;
  }
}

/* 加载状态样式 */
.loading-container {
  @apply flex items-center justify-center py-12;
}

/* 错误状态样式 */
.error-container {
  @apply flex flex-col items-center justify-center py-12 text-center;
}

/* 空状态样式 */
.empty-state {
  @apply flex flex-col items-center justify-center py-12 text-center text-gray-500;
}

.empty-state svg {
  @apply mb-4 text-gray-400;
}

/* 响应式优化 */
@media (max-width: 640px) {
  .browse-header {
    @apply px-2;
  }
  
  .browse-content {
    @apply px-2;
  }
  
  .container {
    @apply px-2;
  }
}

/* 章节卡片过渡动画 */
.chapter-card {
  @apply transition-all duration-200 ease-in-out;
}

.chapter-card:hover {
  @apply shadow-md transform translate-y-[-2px];
}

/* 选中状态的样式增强 */
.chapter-selected {
  @apply ring-2 ring-blue-500 ring-opacity-50;
}

/* 滚动条样式 */
.chapter-scroll::-webkit-scrollbar {
  @apply w-2;
}

.chapter-scroll::-webkit-scrollbar-track {
  @apply bg-gray-100 rounded-full;
}

.chapter-scroll::-webkit-scrollbar-thumb {
  @apply bg-gray-300 rounded-full hover:bg-gray-400;
}
</style>
